import {
  HttpException,
  HttpStatus,
  Injectable,
  ServiceUnavailableException,
} from '@nestjs/common';
import { Repository } from 'typeorm';
import { User } from '../entities/user.entity';
import { InjectRepository } from '@nestjs/typeorm';
import { CreateUserDto } from '../dto/user/create-user.dto';
import { UpdateUserDto } from '../dto/user/update-user.dto';

@Injectable()
export class UserService {
  constructor(
    @InjectRepository(User, 'shop')
    private readonly userRepository: Repository<User>,
  ) {}

  async create(createUserDto: CreateUserDto) {
    try {
      const row = createUserDto;
      delete row.pwdRepeat;
      const user = new User(row);
      const result = await this.userRepository.save(user);
      if (result) {
        return '注册成功';
      }
      return '注册失败';
    } catch (e) {
      throw new ServiceUnavailableException();
    }
  }

  async findOne(id: number) {
    try {
      const res = await this.userRepository.findOneBy({
        id,
        isDelete: 1,
      });
      return res;
    } catch (e) {
      throw new ServiceUnavailableException();
    }
  }

  // 根据用户名查询
  async findUser(username: string) {
    try {
      const user = await this.userRepository
        .createQueryBuilder('custom_user')
        .addSelect('custom_user.password') // 返回密码
        .where('custom_user.username = :username', { username })
        .getOne();

      return user;
    } catch (e) {
      throw new ServiceUnavailableException(e);
    }
  }

  async update(id: number, updateUserDto: UpdateUserDto) {
    try {
      const dbRow = await this.findOne(id);
      if (dbRow) {
        const data = {
          ...dbRow,
          ...updateUserDto,
        };
        const user = new User(data);
        const result = this.userRepository.save(user);
        if (result) {
          return '修改成功';
        }
        return '修改失败';
      } else {
        throw new HttpException('当前数据不存在！', HttpStatus.BAD_REQUEST);
      }
    } catch (e) {
      throw new ServiceUnavailableException();
    }
  }

  async remove(username: string) {
    try {
      const dbRow = await this.findUser(username);
      if (dbRow) {
        const data = {
          ...dbRow,
          is_delete: -1,
        };
        const result = this.userRepository.save(data);
        if (result) {
          return '注销成功';
        }
        return '注销失败';
      } else {
        throw new HttpException('当前数据不存在！', HttpStatus.BAD_REQUEST);
      }
    } catch (e) {
      throw new ServiceUnavailableException();
    }
  }
}
